<template>
     <img :src="captchaUrl" alt="验证码" @click="refreshCaptcha" />  
</template>
<script>
const env = import.meta.env
export default {
    props: ['modelValue'],
    emits: ['update:modelValue'],
    data(){
        return {
            timestamp: Date.now(),
            captchaUrl:'',
            captcha_key:this.modelValue || ''
        }
    },
    watch:{
        modelValue(val,old){
            if(val!=this.captcha_key){
                this.captcha_key = val;
            }
        },
        captcha_key(val,old){
            if(val!=this.value){
                this.$emit('update:modelValue', val); //修改值
            }
        },
    },
    methods: {
        async refreshCaptcha(){
            this.timestamp = Date.now();
            this.captchaUrl = await this.getCaptchaUrl();
        },
        async getCaptchaUrl(){
            const baseURL =  env.VITE_API_BASE_URL || '';
            let path = '/captcha/default';
            //判断API模式
            if(env.VITE_WEB_API_MODEL!='api'){
                return baseURL+path+'?timestamp='+this.timestamp;
            }
            path = '/open/captcha';
            const response = await this.$request.get(path+'?timestamp='+this.timestamp);
            if(response.status==200 && response.data.img){
                this.captcha_key = response.data.key;
                return response.data.img;
            }
            return '';
        }
  },
  mounted(){
    this.refreshCaptcha();
  }
}
</script>